<template>
  <va-modal v-model="isVisible" hide-default-actions title="个人资料">
    <div class="profile-container">
      <va-alert v-if="message.text" :color="message.type" icon="info">
        {{ message.text }}
      </va-alert>
      
      <div class="user-info">
        <va-avatar :color="getAvatarColor" size="large">{{ user?.username?.charAt(0).toUpperCase() }}</va-avatar>
        <h3>{{ user?.username }}</h3>
        <p>角色: {{ user?.role === 'admin' ? '管理员' : '普通用户' }}</p>
      </div>

      <template v-if="isPasswordChangeActive">
        <form @submit.prevent="handlePasswordChange" class="password-form">
          <va-input
            v-model="oldPassword"
            label="当前密码"
            class="mb-3"
            type="password"
            :error="!!oldPasswordError"
            :error-messages="oldPasswordError"
            @update:modelValue="oldPasswordError = ''"
            required
          />
          
          <va-input
            v-model="newPassword"
            label="新密码"
            class="mb-3"
            type="password"
            :error="!!newPasswordError"
            :error-messages="newPasswordError"
            @update:modelValue="newPasswordError = ''"
            required
          />
          
          <va-input
            v-model="confirmPassword"
            label="确认新密码"
            class="mb-3"
            type="password"
            :error="!!confirmPasswordError"
            :error-messages="confirmPasswordError"
            @update:modelValue="confirmPasswordError = ''"
            required
          />
          
          <div class="actions">
            <va-button type="submit" color="primary" :loading="isLoading">
              保存
            </va-button>
            <va-button @click="isPasswordChangeActive = false" flat>
              取消
            </va-button>
          </div>
        </form>
      </template>
      
      <div v-else class="actions">
        <va-button @click="isPasswordChangeActive = true" color="secondary">
          <va-icon name="lock" />
          修改密码
        </va-button>
        <va-button @click="handleLogout" color="danger">
          <va-icon name="logout" />
          退出登录
        </va-button>
      </div>
    </div>
  </va-modal>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useAuth } from '../composables/useAuth'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'logout'])

const { user, logout, changePassword, isLoading, isDefaultAdmin } = useAuth()

const isPasswordChangeActive = ref(false)
const oldPassword = ref('')
const newPassword = ref('')
const confirmPassword = ref('')
const oldPasswordError = ref('')
const newPasswordError = ref('')
const confirmPasswordError = ref('')
const message = ref({ text: '', type: 'info' })

const isVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const getAvatarColor = computed(() => {
  return user.value?.role === 'admin' ? 'primary' : 'secondary'
})

const handleLogout = async () => {
  await logout()
  isVisible.value = false
  emit('logout')
}

const handlePasswordChange = async () => {
  // Reset errors
  oldPasswordError.value = ''
  newPasswordError.value = ''
  confirmPasswordError.value = ''
  message.value = { text: '', type: 'info' }
  
  // Validate
  let isValid = true
  
  if (!oldPassword.value) {
    oldPasswordError.value = '请输入当前密码'
    isValid = false
  }
  
  if (!newPassword.value) {
    newPasswordError.value = '请输入新密码'
    isValid = false
  } else if (newPassword.value.length < 6) {
    newPasswordError.value = '密码长度至少6位'
    isValid = false
  }
  
  if (!confirmPassword.value) {
    confirmPasswordError.value = '请确认新密码'
    isValid = false
  } else if (newPassword.value !== confirmPassword.value) {
    confirmPasswordError.value = '两次输入的密码不一致'
    isValid = false
  }
  
  if (!isValid) return
  
  try {
    // For admin account we simulate the change
    if (isDefaultAdmin.value && oldPassword.value === 'memeking') {
      // Success message and reset form
      message.value = { text: '密码修改成功！', type: 'success' }
      resetPasswordForm()
    } else {
      // Real API call
      await changePassword(oldPassword.value, newPassword.value)
      message.value = { text: '密码修改成功！', type: 'success' }
      resetPasswordForm()
    }
  } catch (error) {
    if (isDefaultAdmin.value) {
      oldPasswordError.value = '当前密码错误'
    } else {
      message.value = { text: '密码修改失败，请重试', type: 'danger' }
    }
  }
}

const resetPasswordForm = () => {
  isPasswordChangeActive.value = false
  oldPassword.value = ''
  newPassword.value = ''
  confirmPassword.value = ''
}
</script>

<style scoped>
.profile-container {
  padding: 1rem 0;
}

.user-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 2rem;
}

.user-info h3 {
  margin-top: 0.5rem;
  margin-bottom: 0.25rem;
}

.password-form {
  margin-top: 1rem;
}

.mb-3 {
  margin-bottom: 0.75rem;
}

.actions {
  display: flex;
  gap: 1rem;
  margin-top: 1.5rem;
  justify-content: center;
}
</style> 